package xiaojian.toolkit.bean.closure;

import java.util.List;

import org.apache.commons.collections4.Closure;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import xiaojian.toolkit.bean.event.EventTypeMetainfo;
import xiaojian.toolkit.ebus.EventBus;

/**
 * 读取请求class发现请求对象对应的事件信息。
 * 
 * @author <a href="mailto:caoxiaojian@wasu.cn">xiaojiancao</a>
 *
 */
public class EventDispatchClosure2 implements Closure {

	private static final Logger logger = LoggerFactory
			.getLogger(EventDispatchClosure2.class);

	private EventBus eventBus;

	private EventTypeMetainfo eventTypeMetainfo = null;

	private Closure nulleventHandler = null;

	/**
	 * @return the nulleventHandler
	 */
	public Closure getNulleventHandler() {
		return nulleventHandler;
	}

	/**
	 * @param nulleventHandler
	 *            the nulleventHandler to set
	 */
	public void setNulleventHandler(Closure nulleventHandler) {
		this.nulleventHandler = nulleventHandler;
	}

	public void setEventTypeMetainfo(EventTypeMetainfo eventTypeMetainfo) {
		this.eventTypeMetainfo = eventTypeMetainfo;
	}

	/**
	 * @see org.apache.commons.collections.Closure#execute(java.lang.Object)
	 */
	public void execute(Object input) {
		if (null == input) {
			return;
		}

		List<String> events = eventTypeMetainfo.find(input.getClass());
		if (null == events || events.isEmpty()) {
			if (null != nulleventHandler) {
				nulleventHandler.execute(input);
			} else {
				logger.warn("can't found event for " + input + ", just ignore.");
			}
			return;
		}

		for (String event : events) {
			eventBus.fireEvent(event, input);

			if (logger.isDebugEnabled()) {
				logger.debug("fire event [" + event + "] <--> " + input);
			}
		}
	}

	public EventBus getEventBus() {
		return eventBus;
	}

	public void setEventBus(EventBus eventBus) {
		this.eventBus = eventBus;
	}

}
